<template>
  <el-card v-loading="isLoading">
    <template #header>
      <div class="card-header">
        <div class="card-header-title">
          <el-icon><Bicycle /></el-icon>
          <span>远郊补贴申报</span>
        </div>
        <el-alert
          :type="
            exceptions.length > 0
              ? 'error'
              : warnings.length > 0
              ? 'warning'
              : 'success'
          "
          :closable="false"
        >
          <!-- <el-text type="info"> -->
          <ul style="padding-left: 1em">
            <li>此页面用于机动组人员提交远郊绩效申报</li>
            <li>仅用于前一日23:59前下席位且次日无席位时申报</li>
            <li>仅在每天00:00至10:30允许8名机动组人员提交申报</li>
            <li>申报人员需在前一日20:00~23:59之间有打卡记录</li>
            <li v-if="!commonStore.isReal">演示模式</li>
          </ul>
          <!-- </el-text> -->
        </el-alert>
      </div>
    </template>
    <template #default>
      <div class="card-body">
        <el-alert
          v-for="item in exceptions"
          :type="item.type"
          :closable="false"
          show-icon
          :title="item.message"
        />
        <el-alert
          v-for="item in warnings"
          :type="item.type"
          :closable="false"
          show-icon
          :title="item.message"
        />
        <el-form label-width="90px">
          <el-form-item label="申报人">
            <el-select v-model="selectedMemberIndex" style="width: 100%">
              <el-option
                v-for="(user, idx) in memberList"
                :value="idx"
                :label="user.name"
              >
                <span style="float: left">{{ user.name }}</span>
                <span
                  style="
                    float: right;
                    color: var(--el-text-color-secondary);
                    font-size: 13px;
                  "
                  >{{ user.uid }}</span
                >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-input
              v-model="startTime"
              :prefix-icon="Clock"
              disabled
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-input
              v-model="endTime"
              :prefix-icon="Clock"
              disabled
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="证明人">
            <el-select v-model="selectedWitnessIndex" style="width: 100%">
              <el-option
                v-for="(user, idx) in witnessList"
                :value="idx"
                :label="user.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template #footer>
      <div class="card-footer">
        <el-button
          type="primary"
          :disabled="exceptions.length > 0 || !(isAvailable && isValid)"
          @click="handleSubmit()"
        >
          <!-- <el-icon><Refresh /></el-icon> -->
          <el-icon>
            <Pointer />
          </el-icon>
          <span>提交</span>
        </el-button>
        <el-button
          type="info"
          link
          v-if="!(commonStore.isReal && isAvailable)"
          @click="loadAvailableMembers"
        >
          <span>重置</span>
        </el-button>
      </div>
    </template>
  </el-card>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { Clock } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";
import axios from "axios";
import dayjs from "dayjs";
import useSeatStore from "@/store/seat.js";
import useCommonStore from "@/store/common.js";

const seatStore = useSeatStore();
const commonStore = useCommonStore();

// 选择的申报人和证明人
const selectedMemberIndex = ref(-1);
const selectedWitnessIndex = ref(-1);

// 添加的虚拟打卡数据时间范围
const startTime = ref("");
const endTime = ref("");

// 申报人列表
const memberList = ref([]);

// 证明人列表
const witnessList = ref([]);

// 正在载入数据
const isLoading = ref(false);

// 可能符合申报人条件的打卡数据（前一日存在打卡记录）
const queryStart = ref("");
const queryEnd = ref("");

// 不符合申报人条件的打卡数据（当日存在打卡记录）
const queryExclusionStart = ref("");
const queryExclusionEnd = ref("");

// 已存在的申报记录
const existedRecoed = ref([]);

// 提交虚拟打卡记录的备注信息
const remark = ref("机动组远郊绩效申报");

// 该小程序禁止使用的情况
const exceptions = computed(() => {
  let result = new Array();
  if (isLoading.value) {
    result.push({ type: "info", message: "正在读取数据……" });
    return result;
  }
  if (commonStore.isReal) {
    // 时间段必须是00:00~10:30
    let now = dayjs();
    let date = now.format("YYYY-MM-DD");
    if (
      !(
        now.isSameOrAfter(date + " 00:00:00") &&
        now.isSameOrBefore(date + " 10:30:00")
      )
    ) {
      result.push({
        type: "error",
        message: "当前不在有效时段, 仅限 00:00 ~ 10:30 使用此功能",
      });
    }
  }
  if (
    !["TM10", "TM14"].includes(seatStore.currentSeat.seatName) &&
    commonStore.isReal
  ) {
    // 席位名称必须是TM10或TM14
    result.push({
      type: "error",
      message: "当前席位不可使用此功能, 仅限 TM10/TM14 席位使用此功能",
    });
  }
  if (memberList.value.length == 0) {
    result.push({
      type: "error",
      message: "未找到昨日有打卡记录的见习人员！",
    });
  }
  if (witnessList.value.length == 0) {
    result.push({
      type: "error",
      message: "未找到代班主任岗打卡记录！",
    });
  }
  return result;
});

// 禁止访问
const isAvailable = computed(() => {
  return exceptions.value && exceptions.value.length == 0;
});

// 提示信息
const warnings = computed(() => {
  let result = new Array();
  if (exceptions.value.length > 0) {
    return result;
  }
  if (selectedMemberIndex.value == null) {
    result.push({
      type: "warning",
      message: "请选择机动组申报人",
    });
  }
  if (selectedWitnessIndex.value == null) {
    result.push({
      type: "warning",
      message: "请选择证明人",
    });
  }
  return result;
});

// 内容符合规范
const isValid = computed(() => warnings.value.length == 0);

const selectedMember = computed(() =>
  isAvailable.value ? memberList.value[selectedMemberIndex.value] : null
);
const selectedWitness = computed(() =>
  isAvailable.value ? witnessList.value[selectedWitnessIndex.value] : null
);

const loadAvailableMembers = async () => {
  // 设置默认时间
  let fakeDate = "2025-06-20 10:00:00";
  let targetDayjs = commonStore.isReal ? dayjs() : dayjs(fakeDate);
  startTime.value = targetDayjs
    .clone()
    .hour(10)
    .minute(0)
    .second(0)
    .format("YYYY-MM-DD HH:mm:ss");
  endTime.value = targetDayjs
    .clone()
    .hour(10)
    .minute(1)
    .second(0)
    .format("YYYY-MM-DD HH:mm:ss");
  queryStart.value = targetDayjs
    .clone()
    .subtract(1, "day")
    .hour(16)
    .minute(0)
    .second(0)
    .format("YYYY-MM-DD HH:mm:ss");
  queryEnd.value = targetDayjs
    .clone()
    .subtract(1, "day")
    .hour(23)
    .minute(59)
    .second(59)
    .format("YYYY-MM-DD HH:mm:ss");
  queryExclusionStart.value = targetDayjs
    .clone()
    .hour(0)
    .minute(0)
    .second(0)
    .format("YYYY-MM-DD HH:mm:ss");
  queryExclusionEnd.value = targetDayjs
    .clone()
    .hour(23)
    .minute(59)
    .second(59)
    .format("YYYY-MM-DD HH:mm:ss");

  try {
    // 载入昨天1100~2359之间存在打卡记录的放单及以上人员
    // begTime 小于等于 23:59:59
    // endTime 大于等于 11:00:00
    // seatRole 小于等于 3

    isLoading.value = true;
    let members = new Array();

    // 查询昨日有打卡的人员
    let response = await axios.post("api/seat_hours_get.php", {
      start: queryStart.value,
      end: queryEnd.value,
    });
    let records = response.data.content.filter((rec) => rec.seatRoleId <= 2);

    // 查询今日有打卡的人员
    let response2 = await axios.post("api/seat_hours_get.php", {
      start: queryExclusionStart.value,
      end: queryExclusionEnd.value,
    });
    let records2 = response2.data.content;

    //  查询今日已申报的人员
    let response3 = await axios.post("api/seat_hours_declaration.php", {
      method: "GET",
      startTime: startTime.value,
      endTime: endTime.value,
      filters: [{ field: "remark", value: remark.value }],
    });
    let records3 = response3.data.content;
    existedRecoed.value = records3;

    // 生成可用人员
    records.forEach((rec) => {
      // members 数组不包含 records[n] 对应的 uid
      // 且 records2 数组不包含 records[n] 对应的 uid
      // 则在 members 数组添加 records[n] 对应的人员信息
      if (
        members.filter((user) => user.uid == rec.userId).length == 0 &&
        records2.filter((rec2) => rec2.userId == rec.userId).length == 0 &&
        records3.filter((rec3) => rec3.userId == rec.userId).length == 0
      ) {
        members.push({
          name: rec.userName,
          uid: rec.userId,
          orgId: rec.orgId,
        });
      }
    });
    members.sort((a, b) => a.uid - b.uid);
    memberList.value = members;
    selectedMemberIndex.value = null;
    console.log("loadAvailableMembers", members);
  } catch (error) {
    console.error("loadAvailableMembers", error);
  } finally {
    isLoading.value = false;
  }

  // 从当前席位信息中查找SUP01或者SUP02席位的打卡人员
  let sups = seatStore.seatStatusFull.filter(
    (cell) =>
      cell.orgGroup == "TMA" &&
      (cell.seatName == "SUP01" || cell.seatName == "SUP02") &&
      cell.users.length > 0
  );
  if (sups.length > 0 && sups[0].users[0].userId) {
    let witnesses = new Array();
    sups.forEach((s) => {
      s.users.forEach((u) => {
        witnesses.push({
          name: u.userName,
          uid: u.userId,
        });
      });
    });
    witnessList.value = witnesses;
    let witnesUser = sups[0].users[0];
    // witness.value = witnesUser.userId;
    selectedWitnessIndex.value = 0;
    console.log("MemberNightWork", "witnesUser", witnesUser);
  } else {
    selectedWitnessIndex.value = null;
    console.error("MemberNightWork", "witnesUser", seatStore.seatStatusFull);
  }
};

const handleSubmit = () => {
  let payload = {
    method: "SET",
    data: [
      {
        userName: selectedMember.value.name,
        userId: selectedMember.value.uid,
        orgId: selectedMember.value.orgId,
        startTime: startTime.value,
        endTime: endTime.value,
        seatCode: "TM01",
        seatRole: "放单",
        seatRoleId: 2,
        seatPost: "协调",
        seatPostId: 2,
        witnessId: selectedWitness.value.uid,
        witnessName: selectedWitness.value.name,
        asHour: 0,
        remark: remark.value,
      },
    ],
  };

  ElMessageBox.confirm("提交后不可撤销，确认信息填写正确吗", "确认", {
    confirmButtonText: "提交",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    isLoading.value = true;
    axios
      .post("api/seat_hours_declaration.php", payload)
      .then((response) => {
        if (response.data.success) {
          ElMessageBox.alert(
            `已提交 ${payload.data[0].userName} 的远郊申报`,
            "已提交",
            { confirmButtonText: "OK" }
          );
        } else {
          ElMessageBox.alert(JSON.stringify(data, null, 2), "出错了", {
            confirmButtonText: "OK",
          });
        }
      })
      .catch((error) => {
        console.error("handleSubmit", error);
        ElMessageBox.alert(JSON.stringify(error, null, 2), "出错了", {
          confirmButtonText: "OK",
        });
      })
      .finally(() => {
        isLoading.value = false;
        loadAvailableMembers();
      });
  });
};

onMounted(() => {
  loadAvailableMembers();
});
</script>

<style scoped>
.card-header {
  width: 100%;
  /* max-width: 480px; */
}

.card-header > *:not(:first-child) {
  margin-top: 1em;
}

.card-header-title {
  font-size: 1.25em;
  font-weight: bolder;
  display: flex;
  align-items: center;
}

.card-header-title > *:not(:first-child) {
  margin-left: 0.5em;
}

.card-body {
  width: 100%;
  /* max-width: 480px; */
}

.card-body > *:not(:first-child) {
  margin-top: 1em;
}

.card-footer {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 12px 0;
}
</style>
